// pages/orderConfirm/orderConfirm.js
var app = getApp();
const Big = require('../../utils/big.js')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    isIphoneX: app.globalData.isIphoneX,
    vipInfo: "",
    fromPage: '', // 页面来源
    address: "", // 地址详情
    freightPrice: 0, // 邮费
    message: "", // 用户留言
    shopList: {}, // 商品详情
    shopPrice: 0, //商品价钱
    couponList: [], // 优惠券列表
    couponIndex: '', // 优惠券下标
    selectIndex: '', // 选择优惠券下标
    vipDiscount: 1, // 会员折扣
    couponDiscount: 1, // 优惠券折扣
    couponCount: 0 // 优惠券优惠价格
  },

  showPopup() {
    this.setData({
      show: true
    });
  },

  onClose() {
    this.setData({
      show: false
    });
  },

  // 调整地址列表
  toAddressList() {
    wx.navigateTo({
      url: '../addressList/addressList?fromType=orderConfirm'
    })
  },

  // 获取地址
  getAddress() {
    let that = this
    wx.get("/api/address/list", res => {
      console.log('==== list ===', res)
      if (res.data.length > 0) {
        let index = 0
        try {
          var value = wx.getStorageSync('addressSelect')
          if (value) {
            index = value
          }
        } catch (e) {
          // Do something when catch error
        }
        this.setData({
          address: res.data[index]
        })
        this.chooseAddress()
        // wx.removeStorage({
        //   key: 'addressSelect'
        // })
      }
    }, fail => {})
  },

  // 选择订单地址计算邮费
  chooseAddress() {
    this.setData({
      freightPrice: 0
    })
    this.data.shopList.forEach((item, index) => {
      wx.get(`${wx.api.mallchooseAddress}${this.data.address.id}?goodsId=${item.goodsId}`, res => {
        console.log('==== chooseAddress ===', res)
        if (res.code == 200) {
          this.setData({
            [`shopList[${index}].freightPrice`]: (res.data).toFixed(2),
            freightPrice: this.data.freightPrice += res.data
          })
        }
      })
    })
  },

  // 增加数量
  addCount(e) {
    let item = e.currentTarget.dataset.item
    let index = e.currentTarget.dataset.index
    this.setData({
      [`shopList[${index}].number`]: item.number + 1
    })
    if (item.number > 99) {
      this.setData({
        [`shopList[${index}].number`]: 99
      })
    }
    this.getShopPrice()
  },

  // 减少数量
  subCount(e) {
    let item = e.currentTarget.dataset.item
    let index = e.currentTarget.dataset.index
    if (item.number <= 1) return
    this.setData({
      [`shopList[${index}].number`]: item.number - 1
    })
    this.getShopPrice()
  },

  bindKeyInput(e) {
    let index = e.currentTarget.dataset.index
    let reg = /^([1-9]\d|\d)$/
    console.log(e.detail.value, reg.test(e.detail.value))
    if (reg.test(e.detail.value)) {
      if (e.detail.value < 1) {
        this.setData({
          [`shopList[${index}].number`]: 1
        })
      } else if (e.detail.value > 99) {
        this.setData({
          [`shopList[${index}].number`]: 99
        })
      } else {
        this.setData({
          [`shopList[${index}].number`]: e.detail.value
        })
      }
    } else {
      if (e.detail.value.length > 1) {
        this.setData({
          [`shopList[${index}].number`]: '99'
        })
      } else {
        this.setData({
          [`shopList[${index}].number`]: ''
        })
      }
    }
  },

  bindKeyBlur(e) {
    let item = e.currentTarget.dataset.item
    let index = e.currentTarget.dataset.index
    if (!item.number) {
      this.setData({
        [`shopList[${index}].number`]: 1
      })
    }
    this.getShopPrice()
  },

  // 重新计算总价
  getShopPrice() {
    let shopPrice = 0
    this.data.shopList.forEach(item => {
      shopPrice += item.price * item.number * 100
    })
    this.setData({
      shopPrice: shopPrice / 100
    })
  },

  // 备注
  msgInput(e) {
    let index = e.currentTarget.dataset.index
    this.setData({
      [`shopList[${index}].message`]: e.detail.value
    })
  },

  selectCoupon(e) {
    let index = e.currentTarget.dataset.index
    console.info(index === this.data.selectIndex ? '' : index)
    this.setData({
      selectIndex: index === this.data.selectIndex ? '' : index
    })
  },

  sureCoupon() {
    this.setData({
      couponIndex: this.data.selectIndex,
      show: false
    })
    this.getCouponCount()
  },

  // 跳转优惠券列表
  toCoupon() {
    wx.setStorage({
      key: "couponFilter",
      data: this.data.shopList,
      success() {
        wx.navigateTo({
          url: '/pages/coupon/coupon?fromPage=ShopOrderConfirm'
        })
      }
    })
  },

  // 获取优惠券列表
  getCouponList() {
    wx.get(`${wx.api.couponList}?type=1`, res => {
      console.info('=== couponList ====', res)
      if (res.code == 200) {
        let couponList = []
        let shopList = this.data.shopList
        for (let index = 0; index < res.data.length; index++) {
          for (let ind = 0; ind < shopList.length; ind++) {
            if ((res.data[index].goodsType == '0' || res.data[index].goodsType == '2' && res.data[index].goodsValue == shopList[ind].goodsId) &&
              (res.data[index].min == 0 || res.data[index].min <= shopList[ind].price)) {
              if (!res.data[index].chooseFlag) { // 双循环 去重
                res.data[index].chooseFlag = true
                couponList.push(res.data[index])
              }
            }
          }
        }
        this.setData({
          couponList: [...couponList]
        })
        this.getCouponCount()
      }
    })
  },

  // 计算优惠券折扣
  getCouponCount() {
    this.setData({
      couponDiscount: 1,
      couponCount: 0
    })
    if (this.data.couponList.length > 0 && this.data.couponIndex !== '') { // 有优惠券
      if (this.data.vipInfo && this.data.vipInfo.level != '0') { // 有会员折扣
        if (this.data.couponList[this.data.couponIndex].type == '3') { // 折扣券
          this.setData({
            couponDiscount: this.data.couponList[this.data.couponIndex].discount
          })
        } else {
          this.setData({
            couponCount: this.data.couponList[this.data.couponIndex].discount
          })
        }

      } else { // 无会员折扣
        if (this.data.couponList[this.data.couponIndex].type == '3') { // 折扣券
          this.setData({
            couponDiscount: this.data.couponList[this.data.couponIndex].discount
          })
        } else {
          this.setData({
            couponCount: this.data.couponList[this.data.couponIndex].discount
          })
        }
      }
    }
  },

  submit() {
    if (!this.data.address) {
      wx.showToast({
        title: '请先填写收货地址',
        icon: 'none',
        duration: 2000
      });
      return
    }
    let that = this
    wx.showLoading({
      mask: true
    })
    wx.getSetting({ // 查询订阅消息
      withSubscriptions: true,
      success(res) {
        wx.hideLoading()
        console.log(res.subscriptionsSetting)
        if (res.gzE2MtWOwgmt9F8VdRMMDM8wclsNKQsPoHf5CwLkOTs == 'accept' || res.gzE2MtWOwgmt9F8VdRMMDM8wclsNKQsPoHf5CwLkOTs == 'reject') { // 同意 或 取消
        } else { // 订阅消息 总还是保持以上选择
          wx.requestSubscribeMessage({
            tmplIds: ['gzE2MtWOwgmt9F8VdRMMDM8wclsNKQsPoHf5CwLkOTs', 'UAjyidlquF2Pr_XvZubo7X-rG7dNFffmTw8i_8qrV7k'],
            success(res) {
              console.log(res)
              // if (res.errMsg == 'requestSubscribeMessage:ok') {
              that.orderSubmit();
              // }
            }
          })
        }
      }
    })
  },

  // 提交订单
  orderSubmit() {
    let params = {
      addressId: this.data.address.id, // 用户地址ID
    }
    var orderPrice = this.data.shopPrice * this.data.vipDiscount * this.data.couponDiscount - this.data.couponCount + this.data.freightPrice
    orderPrice = Big(orderPrice).round(2).toString()
    // 每种商品的价格不能低于0.01
    params.orderPrice = orderPrice > (0.01 * this.data.shopList.length).toFixed(2) ? orderPrice : (0.01 * this.data.shopList.length).toFixed(2)
    if (this.data.fromPage == 'shopCar') {
      params.goodsInfosDetails = []
      this.data.shopList.forEach(item => {
        params.goodsInfosDetails.push({
          cartId: item.id, // 购物车ID
          freightPrice: item.freightPrice, // 邮费
          goodsActualPrice: item.price, // 商品折后单价
          goodsId: item.goodsId, // 商品ID
          number: item.number, // 购买数量
          price: item.price, // 商品单价
          productId: item.productId, // 规格ID
          message: item.message, // 客户留言
        })
      })
    } else {
      let item = this.data.shopList[0]
      params.goodsInfosDetail = {
        cartId: item.id, // 购物车ID
        freightPrice: item.freightPrice, // 邮费
        goodsActualPrice: item.price, // 商品折后单价
        goodsId: item.goodsId, // 商品ID
        number: item.number, // 购买数量
        price: item.price, // 商品单价
        productId: item.productId, // 规格ID
        message: item.message, // 客户留言
      }
    }
    if (this.data.couponList.length > 0 && this.data.couponIndex !== '') {
      params.couponNo = this.data.couponList[this.data.couponIndex].couponNo // 优惠券编号
    }

    console.log('==== submit上传参数 ====', params)

    wx.showLoading({
      mask: true
    })
    wx.post(this.data.fromPage == 'shopCar' ? wx.api.mallcartSubmit : wx.api.mallsubmit, params, res => {
      console.log('==== submit ===', res)
      wx.post(wx.api.mallprepay, {
        orderNos: this.data.fromPage == 'shopCar' ? res.data.orderNos : [res.data.orderNo]
      }, result => {
        console.log('==== prepay ===', result)
        if (result.code == 200) {
          this.doWxPay(result)
        }
      })
    }, fail => {})
  },

  //小程序发起微信支付
  doWxPay(param) {
    wx.requestPayment({
      timeStamp: param.data.timeStamp, //记住，这边的timeStamp一定要是字符串类型的，不然会报错
      nonceStr: param.data.nonceStr,
      package: param.data.package,
      signType: param.data.signType,
      paySign: param.data.paySign,
      success(event) {
        console.log('==== success ====', event);
        wx.showToast({
          title: '支付成功',
          icon: 'success',
          duration: 1000
        });
      },
      fail(error) {
        console.log('==== error ====', error)
        wx.showToast({
          title: '支付失败',
          icon: 'error',
          duration: 1000
        });
      },
      complete(res) {
        wx.hideLoading()
        console.log("pay complete", res)
        let result = "success"
        if (res.errMsg != 'requestPayment:ok') { // 失败
          result = "fail"
        }
        setTimeout(() => {
          wx.reLaunch({
            url: `/pages/result/result?result=${result}&url=/pages/shopOrderList/orderList`,
          })
        }, 1000);
      }
    });
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    console.log('=== options ====', options)
    this.setData({
      fromPage: options.fromPage
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    let that = this
    this.setData({
      vipInfo: app.globalData.vipInfo || wx.getStorageSync('vipInfo')
    })
    wx.getStorage({
      key: 'shopDetail',
      success(res) {
        console.log('==== shopDetail ====', res)
        let shopPrice = 0
        let vipInfo = that.data.vipInfo
        res.data.forEach(item => {
          shopPrice += item.price * item.number * 100
        })
        that.setData({
          shopPrice: shopPrice / 100,
          shopList: res.data,
          vipDiscount: vipInfo.value || 1
        })
        wx.get(wx.api.isLogin, res => {
          console.info('=== isLogin ====', res)
          if (res.code == 200) {
            that.getAddress()
            that.getCouponList() // 优惠券列表
          }
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})